# code by fengxh.
# based on 'params_calc_mlx_script.m' which is written in matlb.
# python code is created at Jun12,2023

from scipy.optimize import curve_fit
import numpy as np
import csv
import sys
import operator
import subprocess



# 取csv文件的第N列，抛弃掉标题栏，返回数组
def load_csv_data(filename, idxBase0):
    data = []  # 存放结果的数组

# 打开CSV文件，并读取数据
    flagDataStart = False;
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        i = 0;
        for row in reader:
            if "Horizontal Offset" in row:
                flagDataStart = True;
                continue;
            if(not flagDataStart): continue;
            try:
               data.append(float(row[idxBase0]))  # 取第一列数据，并转为float类型
            except:
                continue;
    return data;


def getRmsOfFreq(arFreq, arRms, freq):
    for i in range(0, len(arFreq)):
        if(arFreq[i] == freq): return arRms[i];

def csv2trc(csvfile, trcfile, ratio):
# 要执行的命令
#Usage: Csv2Trc <src.csv> <tgt.trc> [<sample_rate=100e-6> <volPerAd>=1]    
    command = r"C:\Users\fengxh\Desktop\工具集\dumb\Csv2Trc_V1.0.20230531\SampleData_CSV2LecoryTrc";
    command = command + " " +csvfile + ' ' + trcfile + ' ' + str(ratio);
    # 执行命令并获取输出
    output = subprocess.check_output(command, shell=True)
    output = output.decode()  # 如果你想要将输出作为字符串处理，可以解码为返回的字节字符串
    print(output)

def toInteger(rms):
    vals = [];
    for i in rms:
        if(not i in vals):
            vals.append(i);

    sorted_vals = sorted(vals);

    my_dict = {sorted_vals[0]:1};
    idx = 1;
    for v in sorted_vals:
        my_dict[v] = idx;
        idx = idx +1;

    ret = [];
    for i in rms:
        ret.append(my_dict[i]);
            
    return ret;


def zoom_out_lecory_wave_data(filename, ratio=1):
    time = load_csv_data(filename, 3);  #freq
    rms = load_csv_data(filename, 4); #rms of freq
    time_min = time[0];
    time_max = time[-1];
    dt = time_max - time_min;

    rms = toInteger(rms);
    
    
    print("数据的时间跨度", dt, "秒");
    data = rms[:];
    
    for i in range(0, len(rms)):
        data[i//round(ratio) + round(i%(round(ratio))*len(rms)/ratio)] = rms[i];

    data_2d = [[element] for element in data]
    filename = filename + '.zoom_out' + str(ratio) + ".csv";
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(data_2d)
    csv2trc(filename, filename+".trc", dt*ratio/len(rms));
    print("done!");


filename = "2308180046_btn.csv";
zoom_out_lecory_wave_data(filename,1);
